package ext.acae2.baseline.ui;

import java.util.ArrayList;
import java.util.Vector;

import wt.fc.Persistable;
import wt.folder.Folder;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.pdmlink.PDMLinkProduct;
import wt.util.WTException;

import com.ptc.core.ui.validation.DefaultSimpleValidationFilter;
import com.ptc.core.ui.validation.UIValidationCriteria;
import com.ptc.core.ui.validation.UIValidationKey;
import com.ptc.core.ui.validation.UIValidationStatus;

import ext.acae2.ACAEConstants;
import ext.acae2.utilities.principal.CSCPrincipal;

/**
 * @desription baseline create validator
 * @author cnie
 * @date 2013-3-20 上午10:06:02
 */
public class BaselineCreateFilter extends DefaultSimpleValidationFilter{

	@Override
	public UIValidationStatus preValidateAction(UIValidationKey uivalidationkey,
			UIValidationCriteria uivalidationcriteria) {
		UIValidationStatus status = UIValidationStatus.HIDDEN;
		try {
			Vector<WTUser> userVector = new Vector<WTUser>();
			Persistable p = uivalidationcriteria.getContextObject().getObject();
			PDMLinkProduct product = null;
			if(p instanceof Folder){
				Folder folder = (Folder)p;
				Persistable productper = folder.getContainerReference().getObject();
				if(productper instanceof PDMLinkProduct){
					product = (PDMLinkProduct)productper;
				}
			}else if(p instanceof PDMLinkProduct){
				product = (PDMLinkProduct)p;
			}
			WTPrincipal currentUser = uivalidationcriteria.getUser().getPrincipal();
			//PDMLinkProduct product = QueryUtil.getProductByName("CJ-1000AX");
			ArrayList<WTPrincipalReference> principalRefs = CSCPrincipal.getPrinciaplByRole(product, ACAEConstants.ROLE_BASELINEMANAGER);
			for(WTPrincipalReference principalRef: principalRefs){
				WTPrincipal principal = principalRef.getPrincipal();
				if(principal instanceof WTGroup){
					WTGroup group = (WTGroup)principal;
					userVector = CSCPrincipal.getGroupMemberUsers(group, userVector);
				}else if(principal instanceof WTUser){
					WTUser user = (WTUser)principal;
					if(!userVector.contains(user)){
						userVector.add(user);
					}
					
				}
			}
			if(userVector.contains(currentUser)){
				status=UIValidationStatus.ENABLED;
			}
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return status;
	}
	
	

}
